<template>
  <div class="page">
    <!-- 顶部导航栏 -->
    <header class="header">
      <div class="logo">知识图谱</div>
    </header>

    <!-- 主体内容区域 -->
    <div class="main-content">

      <!-- 中央区域（使用 Map.vue 组件） -->
      <section class="main-visual">
        <MapUtil/>
      </section>

      <!-- 右侧栏（包含AI聊天功能） -->
      <aside class="right-sidebar">
        <div class="chat-container">
          <div class="status-indicator">
            <span class="online-dot"></span>
            <h3 class="assistant-title">游戏策划AI小助手</h3>
          </div>
          <div class="message-list">
            <div v-for="(msg, index) in messages" :key="index" :class="['message', msg.role]">
              <div class="avatar">{{ msg.role === 'user' ? '👤' : '🤖' }}</div>
              <div class="bubble">{{ msg.text }}</div>
            </div>
            <div v-if="isTyping" class="message ai">
              <div class="avatar">🤖</div>
              <div class="bubble typing">{{ currentAIText }}<span class="cursor">|</span></div>
            </div>
          </div>
          <div class="input-area">
            <input v-model="userInput" @keyup.enter="sendMessage" placeholder="输入消息..."
                   :disabled="isWaitingResponse"/>
            <button @click="sendMessage" :disabled="isWaitingResponse">发送</button>
          </div>
        </div>
      </aside>
    </div>
  </div>
</template>

<script>
import MapUtil from '@/components/MapUtil.vue';

export default {
  name: 'GameDesignKnowledgeMap',
  components: {
    MapUtil,
  },
  data() {
    return {
      messages: [],
      userInput: "",
      currentAIText: "",
      isTyping: false,
      isWaitingResponse: false,
      typingSpeed: 20,
      typingTimer: null,
      abortController: null, // 用于取消请求
    };
  },
  mounted() {
  },
  methods: {
    async sendMessage() {
      if (!this.userInput.trim() || this.isWaitingResponse) return;

      // 1. 添加用户消息
      this.messages.push({
        role: "user",
        text: this.userInput,
      });
      const userMessage = this.userInput;
      this.userInput = "";
      this.isWaitingResponse = true;

      // 2. 创建AbortController以便取消请求
      this.abortController = new AbortController();

      try {
        // 构建请求URL（替换为你的实际appId和secretKey）
        const appId = "YTk2ejbUc1TDsr0Q28WbpDBM3P6TtOdG";
        const secretKey = "VF9BaoswFxgbi1oA3cFLKIShRZg4mqgm";
        const url = `https://agentapi.baidu.com/assistant/conversation?appId=${appId}&secretKey=${secretKey}`;

        // 构建请求体
        const requestBody = {
          message: {
            content: {
              type: "text",
              value: {
                showText: userMessage
              }
            }
          },
          source: "appAnsId",
          from: "openapi",
          openId: localStorage.getItem('id') // 使用本地存储的用户ID
        };

        const response = await fetch(url, {
          method: "POST",
          headers: {"Content-Type": "application/json"},
          body: JSON.stringify(requestBody),
          signal: this.abortController.signal,
        });

        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }

        if (!response.body) {
          throw new Error("ReadableStream not supported in this browser");
        }

        // 3. 处理流式响应
        const reader = response.body.getReader();
        const decoder = new TextDecoder("utf-8");
        let fullText = "";
        let buffer = "";
        let reading = true;

        while (reading) {
          const {done, value} = await reader.read();
          reading = !done;

          if (value) {
            buffer += decoder.decode(value, {stream: true});

            // 处理可能的多行数据
            const lines = buffer.split(/\r\n|\n|\r/);
            buffer = lines.pop() || "";

            for (const line of lines) {
              if (line.startsWith("data:")) {
                try {
                  const jsonStr = line.substring(5).trim();
                  if (jsonStr) {
                    const data = JSON.parse(jsonStr);
                    const newText = this.extractAIText(data);
                    if (newText) {
                      fullText += newText;
                      this.playTypingEffect(newText);
                    }
                  }
                } catch (err) {
                  console.error("解析错误:", err);
                }
              }
            }
          }
        }

        // 处理剩余缓冲区数据
        if (buffer.trim()) {
          try {
            const data = JSON.parse(buffer.substring(5).trim());
            const newText = this.extractAIText(data);
            if (newText) {
              fullText += newText;
              this.playTypingEffect(newText);
            }
          } catch (err) {
            console.error("最终解析错误:", err);
          }
        }

        // 添加完整的AI响应
        this.messages.push({
          role: "ai",
          text: fullText,
        });
      } catch (err) {
        if (err.name === "AbortError") {
          console.log("请求已被取消");
        } else {
          console.error("请求失败:", err);
          this.messages.push({
            role: "ai",
            text: "抱歉，AI暂时无法响应，请稍后再试。",
          });
        }
      } finally {
        this.isWaitingResponse = false;
        this.isTyping = false;
        this.currentAIText = "";
        clearInterval(this.typingTimer);
        this.abortController = null;
      }
    },

    // 取消请求的方法
    cancelRequest() {
      if (this.abortController) {
        this.abortController.abort();
      }
    },

    // 从API响应中提取AI文本
    extractAIText(data) {
      let result = "";
      if (data?.data?.message?.content) {
        data.data.message.content.forEach((item) => {
          if (item.data?.text) {
            result += item.data.text;
          }
        });
      }
      return result;
    },

    // 打字机效果
    playTypingEffect(fullText) {
      this.isTyping = true;
      clearInterval(this.typingTimer);

      let i = 0;
      this.typingTimer = setInterval(() => {
        if (i < fullText.length) {
          this.currentAIText += fullText.charAt(i);
          i++;
        } else {
          clearInterval(this.typingTimer);
        }
      }, this.typingSpeed);
    },

    // 初始化ECharts图表的方法在这里不再需要，因为使用了 Map.vue 组件
  },
  beforeUnmount() {
    this.cancelRequest();
    clearInterval(this.typingTimer);
  },
};
</script>

<style scoped>
/* 页面布局 */
.page {
  font-family: "Source Han Sans", sans-serif;
  padding: 20px;
}

/* 顶部导航栏 */
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #082A60;
  padding: 10px;
}

.logo {
  color: #EEEEEE;
  font-size: 18px;
}

/* 主体内容区域 */
.main-content {
  display: flex;
  margin-top: 30px;
  margin-bottom: 30px;
  overflow: hidden;
  height: calc(100vh - 120px); /* 新增动态高度计算 */
}

/* 左侧栏（文本超链接） */
.left-sidebar {
  width: 25%;
  height: 610px;
  background: linear-gradient(360deg, rgb(38 40 48), rgb(8, 42, 96));
  padding: 10px;
  border-right: 1px solid #ddd;
}

.sidebar-item {
  display: block;
  color: white;
  padding: 10px;
  text-decoration: none;
  border-bottom: 1px solid #555;
}

.sidebar-item:hover {
  background-color: rgba(102, 134, 216, 0.61);
  color: #FFFFFF;
}

/* 中间区域（使用 Map.vue 组件） */
.main-visual {
  width: 75%;
  height: 100%;
  background: #fff;
  border: 2px solid #e4e7ed;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, .1);
}

/* 右侧栏 */
.right-sidebar {
  width: 25%;
  background: linear-gradient(360deg, rgb(255, 255, 255), rgb(8, 42, 96));
  padding: 20px;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  border-left: 1px solid #ddd;
  height: 590px;
  overflow-y: auto;
}

/* AI聊天区域 */
.chat-container {
  display: flex;
  flex-direction: column;
  border-radius: 12px;
  padding: 20px;
  height: 100%;
}

/* 消息气泡 */
.bubble {
  padding: 12px 18px;
  border-radius: 15px;
  font-size: 14px;
  line-height: 1.5;
  max-width: 80%;
  transition: transform 0.2s;
}

.user .bubble {
  background: linear-gradient(135deg, #1890ff, #096dd9);
  color: #fff;
  border-radius: 15px 15px 4px 15px;
}

.ai .bubble {
  background: #3d3d3d;
  color: black;
  border-radius: 15px 15px 15px 4px;
}

/* 消息列表 */
.message-list {
  flex: 1;
  overflow-y: auto;
  min-height: 0;
  scrollbar-width: none; /* Firefox */
  -ms-overflow-style: none; /* IE/Edge */
}

.message-list::-webkit-scrollbar {
  width: 0;
  background: transparent;
}

.message {
  display: flex;
  margin-bottom: 12px;
}

.avatar {
  margin-right: 10px;
  font-size: 20px;
}

.bubble {
  max-width: 70%;
  padding: 10px 15px;
  border-radius: 18px;
  line-height: 1.4;
}

.user {
  justify-content: flex-start;
  flex-direction: row-reverse;
}

.user .avatar {
  margin-left: 10px;
}

.ai {
  justify-content: flex-start;
}

.ai .bubble {
  background: white;
  border: 1px solid #eee;
}

.typing {
  position: relative;
}

.cursor {
  animation: blink 1s infinite;
}

@keyframes blink {
  0%, 100% {
    opacity: 1;
  }
  50% {
    opacity: 0;
  }
}

.input-area {
  border-radius: 25px;
  padding: 8px 15px;
  margin-top: 15px;
  background: white;
  height: 60px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.input-area input {
  flex: 1;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 20px;
  height: 30px;
}

.input-area button {
  margin-left: 8px;
  padding: 8px 16px;
  height: 40px;
  background: #1890ff;
  color: white;
  border: none;
  border-radius: 20px;
  cursor: pointer;
}

.status-indicator {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 15px;
}

.online-dot {
  display: inline-block;
  width: 10px;
  height: 10px;
  background: #00ff00;
  border-radius: 50%;
  margin-right: 8px;
  animation: pulse 1.5s infinite;
  box-shadow: 0 0 8px rgba(0, 255, 0, 0.5);
}

.assistant-title {
  color: white;
  font-size: 16px;
  margin: 0;
}

</style>